/**
 * @Description：简易数据流
 * @Data: 2022/3/23
 */
import { useState, useCallback, useEffect } from 'react';
import { history, useAliveController } from 'umi';
import { getMenu, getTask } from '@/services/sysInfo';
import _ from 'lodash';
import { message } from 'antd';
import { getToken } from '@/services/user';
export default () => {
  const [sysInfo, setSysInfo] = useState<API.SysInfo>();
  const [curPermID, setCurPermID] = useState<number>(0);
  const [flowDoing, setFlowDoing] = useState<API.FlowDoing>();
  const [curPath, setCurPath] = useState<string>('');
  const [bodyHeight, setBodyHeight] = useState<number>(document.body.offsetHeight);
  const [tabDatas, setTabDatas] = useState<API.TabData[]>([]);
  const [scrollbarWidth, setScrollbarWidth] = useState<number>(0);
  const { drop, dropScope, clear } = useAliveController();
  const resizeHandler = (): void => {
    setBodyHeight(document.body.offsetHeight);
  };
  useEffect(() => {
    window.addEventListener('resize', resizeHandler);
    const scrollDiv = document.createElement('div');
    scrollDiv.style.cssText =
      'width: 99px; height: 99px; overflow: scroll; position: absolute; top: -9999px;';
    document.body.appendChild(scrollDiv);
    const width = scrollDiv.offsetWidth - scrollDiv.clientWidth;
    document.body.removeChild(scrollDiv);
    setScrollbarWidth(width);
    return () => {
      window.removeEventListener('resize', resizeHandler);
    };
  }, []);
  useEffect(() => {
    if (sysInfo !== undefined) {
      return;
    }
    const token = getToken();
    if (!token) {
      return;
    }
    getMenu()
      .then(function (data) {
        setSysInfo(data);
      })
      .catch(function (ex) {
        console.error('请求系统菜单错误', ex);
      });
  }, [sysInfo]);
  const loadFlowDoing = useCallback((): void => {
    const token = getToken();
    if (!token) {
      return;
    }
    getTask()
      .then(function (data) {
        setFlowDoing(data);
      })
      .catch(function (ex) {
        console.error('请求代办事宜出错', ex);
      });
  }, []);
  useEffect(() => {
    loadFlowDoing();
  }, [loadFlowDoing]);
  useEffect(() => {
    if (_.isEmpty(sysInfo)) {
      return;
    }
    const toMenu = (key: string) => {
      if (key === '/') {
        return;
      }
      const findMenu = (mData: API.MenuData[] | undefined): API.MenuData | undefined => {
        if (_.isEmpty(mData)) {
          return undefined;
        }
        for (let index = 0; index < mData!.length; index++) {
          if (mData![index].path === key) {
            return mData![index];
          }
          const cs = mData![index].routes;
          if (!_.isEmpty(cs)) {
            const m = findMenu(cs);
            if (m) {
              return m;
            }
          }
        }
        return undefined;
      };
      const sDatas = sysInfo?.menuDatas;
      let mData: API.MenuData | undefined;
      if (key.indexOf('changepwd') !== -1) {
        mData = { id: -2, name: '修改密码', path: key };
      } else {
        mData = findMenu(sDatas);
      }
      if (mData !== undefined) {
        const index = tabDatas.findIndex((t) => t.id === mData!.id);
        setCurPath(key);
        setCurPermID(mData.id);
        if (index === -1) {
          tabDatas.push({ tab: mData.name, key: mData.path, id: mData.id });
          setTabDatas(tabDatas);
        }
      }
    };
    if (_.isEmpty(tabDatas)) {
      toMenu(history.location.pathname);
    }
    history.listen((location) => {
      const key = location.pathname;
      toMenu(key);
    });
  }, [tabDatas, sysInfo]);
  const updateSysInfo = useCallback((si) => setSysInfo(si), []);
  const delTab = useCallback(
    (key: string): void => {
      const index = tabDatas.findIndex((t) => t.key === key);
      if (index === -1) {
        return;
      }
      if (drop) {
        drop(key);
        dropScope(key);
      }
      let curTab: API.TabData | undefined = undefined;
      if (tabDatas[index - 1] !== undefined) {
        curTab = tabDatas[index - 1];
      } else if (tabDatas[index + 1] !== undefined) {
        curTab = tabDatas[index + 1];
      }
      if (!curTab) {
        return;
      }
      tabDatas.splice(index, 1);
      setCurPath(curTab!.key);
      setCurPermID(curTab!.id);
      setTabDatas(tabDatas);
      history.push(curTab!.key);
    },
    [drop, dropScope, tabDatas],
  );
  const clearTabDatas = useCallback((): void => {
    clear();
    setTabDatas([]);
  }, [clear]);
  const getCurPermTypes = useCallback((): string[] => {
    if (_.isEmpty(sysInfo?.popedomTypes)) {
      return [];
    }
    return sysInfo!.popedomTypes![curPermID];
  }, [sysInfo, curPermID]);
  const getCurExtendProps = useCallback((): Record<string, any> => {
    try {
      if (_.isEmpty(sysInfo?.popedomTypes)) {
        return {};
      }
      const propStr = sysInfo!.extendProps![curPermID];
      if (_.isEmpty(propStr)) {
        return {};
      }
      return JSON.parse(propStr);
    } catch (ex) {
      message.error(`解析菜单ID:${curPermID}的属性出错`);
      return {};
    }
  }, [sysInfo, curPermID]);
  const clearOtherTabDatas = useCallback(
    (key: string): void => {
      let index = -1;
      tabDatas.forEach((t, i) => {
        if (t.key === key) {
          index = i;
        } else if (drop) {
          drop(t.key);
          dropScope(t.key);
        }
      });
      if (index !== -1) {
        setTabDatas([tabDatas[index]]);
      }
    },
    [drop, dropScope, tabDatas],
  );
  return {
    sysInfo,
    curPermID,
    curPath,
    bodyHeight,
    tabDatas,
    flowDoing,
    scrollbarWidth,
    updateSysInfo,
    delTab,
    clearTabDatas,
    clearOtherTabDatas,
    getCurPermTypes,
    getCurExtendProps,
    loadFlowDoing,
  };
};
